#include <string>
#include "MyBLE.h"

std::string SERVICE_UUID="b408e1a0-3d8a-11ed-b878-0242ac120002";
std::string CHARACTERISTIC_UUID="de045162-3d97-11ed-b878-0242ac120002";

BLECharacteristic chartic(CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);

class ServerCallback: public BLEServerCallbacks{
  void onConnect(BLEServer* server) {
    //Serial.println("DEVICE_CONNECTED~");
    BLEDevice::stopAdvertising();
  }

  void onDisconnect(BLEServer* server) {
    //Serial.println("DEVICE_DISCONNECT~");
    BLEDevice::startAdvertising();
  }
};

class CharticCallback: public BLECharacteristicCallbacks{

public:
  myFun myCB;

  void onRead(BLECharacteristic * characteristic){
    //Serial.println("ON_READ~");
  }

  void onWrite(BLECharacteristic * characteristic){
    std::string data=characteristic->getValue();
    if(data.length()>0){
      String strs="";
      for (int i = 0; i < data.length(); i++){
        strs += (char)data[i];
      }
      //Serial.println("get data:"+strs);
    }
    Serial.println("data:"+String(data.c_str()));
    myCB(data);
  }
};

CharticCallback charCallback=CharticCallback();

void MyBLE::initBLE(const std::string &BLEName, const std::string &serviceUUID, const std::string &charUUID, myFun callback){
  SERVICE_UUID=serviceUUID;
  CHARACTERISTIC_UUID=charUUID;
  charCallback.myCB=callback;

  BLEDevice::init(BLEName);
  BLEServer *server = BLEDevice::createServer();
  BLEService *service = server->createService(SERVICE_UUID);

  service->addCharacteristic(&chartic);
  chartic.addDescriptor(new BLE2902());

  server->setCallbacks(new ServerCallback());
  chartic.setCallbacks(&charCallback);

  service->start();
  BLEDevice::startAdvertising();
}

void MyBLE::sendBackData(std::string &s){
  chartic.setValue(s);
  chartic.notify();
}
